package com.bjsxt.base.lockDesign.design1;

/**
 * 可重入锁
 *
 * lock一次之后, 首先其他线程必定无法进入lock()后的代码, 但本线程其他挂了lock()的地方则可以进入
 */
public class ReLock {

    private boolean isLocked = false;
    private Thread lockedBy = null;
    private int lockedCount = 0; // 可重入锁都必须有个count变量

    public synchronized void lock() throws InterruptedException {
        Thread thread = Thread.currentThread();
        while (isLocked && lockedBy != thread) {
            wait();
        }
        isLocked = true;
        lockedCount++;
        lockedBy = thread;
    }

    public synchronized void unlock() {
        if (Thread.currentThread() == this.lockedBy) {
            lockedCount--;
            if (lockedCount == 0) {
                isLocked = false;
                notify();
            }
        }
    }
}
